<?php
namespace App\Jobs;

use App\Models\StatusCode;
use Illuminate\Support\Facades\Log;
use tinymeng\tools\HttpRequest;

class OrderCallbackJob extends CommonJob
{
    public $order;


    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($order)
    {
        $this->order = $order;
    }

    /**
     * Execute the job.
     *
     * @return bool
     */
    public function handle(){
        $order = $this->order;
        $params = [
            'app_id'=>$order['app_id'],
            'out_trade_no'=>$order['out_trade_no'],
            'transaction_id'=>$order['transaction_id'],
            'amount'=>$order['amount'],
            'payment_method'=>$order['payment_method'],
            'method'=>$order['method'],
            'pay_time'=>$order['pay_time'],
            'is_pay'=>$order['is_pay'],
        ];
        $url = $order['notify_url']??'';
        $logData = ['url'=>$url, 'params'=>$params,];
        if(empty($url)){
            $this->log('回调地址为空 error',$logData);
            return true;
        }

        try{
            $request = HttpRequest::httpPost($url,$params);
            $logData['result'] = $request;
            $result = json_decode($request,true);
            if(empty($result['code']) || $result['code']!=StatusCode::COMMON_SUCCESS){
                $this->log('回调返回 error',$logData);
                return false;
            }
            $this->log('回调请求 success',$logData);
            $order->notify_time = time();//异步成功回调事件
            $order->save();
            return true;
        }catch (\Exception $exception){
            $this->log('回调请求 error',$logData,$exception);
            return false;
        }
    }

    /**
     * 失败重试延迟
     * Calculate the number of seconds to wait before retrying the job.
     *
     * @return array<int, int>
     */
    public function backoff(): array
    {
        return [5, 10 ,60 ,600];
    }


    /**
     * @param $msg
     * @return void
     */
    static public function log($msg,$data=[],$exception=null){
        $str = "【".$msg."】";
        if(!empty($exception) && $exception instanceof \Exception){
            $data['file'] = $exception->getFile();
            $data['line'] = $exception->getLine();
            $data['message'] = $exception->getMessage();
        }
        if(!empty($data)){
            foreach ($data as $key=>$value){
                $str .= ' '.$key.':'.(is_array($value)?json_encode($value):$value).' , ';
            }
        }
        Log::channel('orderCallback')->info($str."\r\n");
    }

}
